package com.atguigu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;


// 旁路缓存改造优化
public class DimUtil {
    public static JSONObject getDimInfo(Connection connection, String table, String key) throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {

        // 获取redis连接
        Jedis jedis = RedisUtil.getJedis();
        // 生成rediskey
        String redisKey = "DIM:" + table + ":" + key;
        String value = jedis.get(redisKey);
        if (value != null){
            // 转换redis的存储值
            JSONObject jsonObject = JSON.parseObject(value);
            // 重置过期时间
            jedis.expire(redisKey, 5 * 60 * 60);
            // 关闭连接
            jedis.close();

            // 返回查询结果
            return jsonObject;
        }


        // 拼接查询语句
        String querySql = "select * from " +
                GmallConfig.HBASE_SCHEMA +
                "." +
                table +
                " where id = '" +
                key + "'";
        System.out.println(querySql);

        // 查询
        JSONObject jsonObject = JDBCUtil.queryList(connection, querySql, JSONObject.class, false).get(0);

        // 将查询结果缓存到redis中
        jedis.set(redisKey, jsonObject.toJSONString());
        jedis.expire(redisKey, 5 * 60 * 60);
        jedis.close();


        // 返回结果
        return jsonObject;

    }

    // 在维度数据发生修改时， 删除redis中对应的缓存数据
    public static void deleteRedisDimInfo(String table, String key){
        Jedis jedis = RedisUtil.getJedis();
        String redisKey =  "DIM:" + table + ":" + key;

        jedis.del(redisKey);

        jedis.close();

        System.out.println("从redis删除缓存！！！ key: " + redisKey);
    }

    public static void main(String[] args) throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "12")); //247  251  271  277  263  260

//        long start = System.currentTimeMillis();
//        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "13")); //9 9
//        long end = System.currentTimeMillis();

//        System.out.println(end - start);

        connection.close();

    }
}
